package com.cyf.plc.ui.fragment

import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.cyf.library.util.loge
import com.cyf.library.util.logi
import com.cyf.plc.R
import com.cyf.plc.adapter.FaultAdapter
import com.cyf.plc.base.BaseFragment
import com.cyf.plc.databinding.FragmentFaultBinding
import com.cyf.plc.model.PlcFault
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.util.viewModelOf
import com.cyf.plc.viewmodel.PlcViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

@ExperimentalCoroutinesApi
class PlcFaultFragment : BaseFragment<PlcViewModel, FragmentFaultBinding>(),
    FaultAdapter.OnItemClickListener {

    override fun layoutId(): Int = R.layout.fragment_fault

    private val mAdapter: FaultAdapter by lazy { FaultAdapter(onItemClickListener = this) }

    var plcFaultList: List<PlcFault> = ArrayList()

    override fun initView() {

        //初始化适配器
        val divider = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        val drawable: Drawable =
            context?.let { ContextCompat.getDrawable(it, R.drawable.drawable_custom_divider) }!!
        drawable.setBounds(0, 0, 4, 0)
        divider.setDrawable(drawable)

        // Initialize RecyclerView
        mViewBinding.rvFault.apply {
            layoutManager = LinearLayoutManager(this.context)
            adapter = mAdapter
            addItemDecoration(divider)
        }
        //Initialize data
        this.plcFaultList = PlcExecutor.plcFaultList
        ("Plc fault list:$plcFaultList").logi()
        mAdapter.submitList(plcFaultList.toMutableList())
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getPlcFault(plcFault: PlcFault) {
        //todo 更新故障显示
        "update fault:$plcFault".loge()
        for ((index, localPlcFault) in plcFaultList.withIndex()) {
            if (localPlcFault.offSet == plcFault.offSet) {
                println("下标=$index----元素=$localPlcFault")
                localPlcFault.faultStatus = plcFault.faultStatus
                //更新故障显示，有故障则变红，故障消失则变黑
                mAdapter.submitList(plcFaultList.toMutableList())
                mAdapter.notifyItemChanged(index)
            }
        }
    }

    override fun createViewModel(): PlcViewModel = viewModelOf(mViewModelProvider)

    override fun onItemClicked(plcFault: PlcFault) {

    }

}